package cn.lili.modules.grab.xdxt;

import cn.lili.common.utils.ResultUtil;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.grab.GrabGoodsParam;
import cn.lili.modules.grab.enums.SourceEnums;
import cn.lili.modules.grab.factory.goods.GrabGoodsService;
import cn.lili.modules.grab.xdxt.facade.GrabXdxtGoodsFacade;
import cn.lili.modules.grab.xdxt.reps.goods.GoodsCateReps;
import cn.lili.modules.grab.xdxt.reps.goods.ListGoodsReps;
import cn.lili.modules.grab.xdxt.res.goods.ListGoodsRes;
import cn.lili.modules.grab.xdxt.service.XdxtGoodsService;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.schl.api.utils.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class GrabXdxtGoodsServiceImpl implements GrabGoodsService {

    @Resource
    private GrabXdxtGoodsFacade grabXdxtGoodsFacade;
    @Resource
    private XdxtGoodsService xdxtGoodsService;

    @Override
    public SourceEnums step() {
        return SourceEnums.XDXT_GOODS;
    }

    /**
     * 商品分类查询
     *
     * @return 查询结果
     */
    public ResultMessage<Object> goodsCate(GrabGoodsParam grabGoodsParam) {
        try {
            GoodsCateReps goodsCateReps = xdxtGoodsService.goodsCate();
            //过滤顶级分类
            grabXdxtGoodsFacade.recursionCategory(grabGoodsParam.getStoreId(), goodsCateReps, -1, -1);
            return ResultUtil.data(goodsCateReps);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 商品全量/选品库查询
     *
     * @return 查询结果
     */
    public ResultMessage<Object> goodsList(GrabGoodsParam grabGoodsParam) {
        try {
            //商品全量/选品库查询
            ListGoodsReps listGoodsReps = xdxtGoodsService.goodsList(grabGoodsParam.getListGoodsRes());
            //处理业务逻辑
            if (listGoodsReps.getResult().getRecords() != null && !listGoodsReps.getResult().getRecords().isEmpty()) {
                for (ListGoodsReps.Result.Records records : listGoodsReps.getResult().getRecords()) {
                    //初始化商品 + SKU
                    grabXdxtGoodsFacade.goodsInit(grabGoodsParam.getStoreId(), records);
                }
            }

            if (grabGoodsParam.getFlag()) {
                //递归继续查找
                ListGoodsRes listGoodsRes = grabGoodsParam.getListGoodsRes();
                listGoodsRes.setCurrent(String.valueOf(Integer.parseInt(listGoodsRes.getCurrent()) + 1));
                grabGoodsParam.setListGoodsRes(listGoodsRes);
                goodsList(grabGoodsParam);
            }
            return ResultUtil.data(listGoodsReps);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
